﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.TextUtils;

using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using System;
using System.Collections.Generic;
using System.Net;

namespace RabbitDownload.WebSite.Pixiv.PixivTag
{
    internal class PixivTagScanner
    {
        /// <summary>
        /// 如果未登录的时候，最后一次请求不会返回null，而是不断地重复返回，所以需要这个判断
        /// </summary>
        private static List<int> TempImgIDList = new List<int>();

        /// <summary>
        /// 普通检索模式
        /// </summary>
        /// <param name="Tags"></param>
        /// <param name="Score"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="DownMaxCount"></param>
        internal static void Start(string Tags, int Score, int StartPage, int EndPage, int DownMaxCount)
        {
            TempImgIDList = new List<int>();
            String API = string.Format(PixivStaticValue.SearchTagApi, WebHelper.UrlEncode(Tags), "{0}");
            RunScanner(Tags, Score, StartPage, EndPage, DownMaxCount, API);
        }

        /// <summary>
        /// 支持时间的检索模式
        /// </summary>
        /// <param name="Tags"></param>
        /// <param name="Score"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="DownMaxCount"></param>
        internal static void StartForTimeMode(string Tags, int Score, int StartPage, int EndPage, int DownMaxCount, DateTime dateTime, int BackwardTime)
        {
            TempImgIDList = new List<int>();
            String API = string.Format(PixivStaticValue.SearchTagApiForTime, WebHelper.UrlEncode(Tags), "{0}", dateTime.AddDays(-BackwardTime).ToString("yyyy-MM-dd"), dateTime.ToString("yyyy-MM-dd"));
            RunScanner(Tags, Score, StartPage, EndPage, DownMaxCount, API);
        }

        /// <summary>
        /// 启动扫描
        /// </summary>
        /// <param name="Tags"></param>
        /// <param name="Score"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="DownMaxCount"></param>
        /// <param name="API"></param>
        private static void RunScanner(string Tags, int Score, int StartPage, int EndPage, int DownMaxCount, string API)
        {
            if (EndPage != 0 && StartPage > EndPage)
            {
                MessageHelper.Alert("起始页不能大于结束页！");
                return;
            }
            List<string> AllImgUrl = new List<string>();
            int Jumpcount = 0;
            for (int i = StartPage; EndPage == 0 || i < EndPage; i++)
            {
                String TempAPI = string.Format(API, i);

                List<String> ImgTemp = AnalysisJson(TempAPI, Score);

                #region
                //判断连续空三次后跳出
                if (ImgTemp == null)
                {
                    Console.WriteLine("无变化{0}次，预备跳出！", Jumpcount++);
                    if (Jumpcount == 3)
                        break;
                }
                else
                {
                    AllImgUrl.AddRange(ImgTemp);
                    Jumpcount = 0;
                }

                #endregion

                if (DownMaxCount != 0 && DownMaxCount < AllImgUrl.Count)
                {
                    Console.WriteLine("达到预设数量，跳出！");
                    break;
                }
            }
            WebCurrency.SaveHelper.AutoSave(AllImgUrl, "P站标签", Tags);
        }

        /// <summary>
        /// 分析JSON，返回图片列表
        /// </summary>
        /// <param name="API"></param>
        /// <param name="Score"></param>

        /// <returns></returns>
        private static List<string> AnalysisJson(string API, int Score)
        {
            List<string> ImglistTemp = new List<string>();
            WebHeaderCollection webHeaderCollection = new WebHeaderCollection();

            webHeaderCollection.Add("Host", new Uri(API).Host);
            webHeaderCollection.Add("User-Agent", StaticValueOld.MoblieUserAgent);
            webHeaderCollection.Add("Accept-Language", "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            webHeaderCollection.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            webHeaderCollection.Add("Accept-Language", "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            webHeaderCollection.Add("Pragma", "no-cache");
            webHeaderCollection.Add("Cache-Control", "no-cache");
            string Shtml = WebHelper.HttpGet(API, webHeaderCollection);
            if (Shtml.Length < 100)
                return null;
            PixivTagJson.Root AllJson = JsonConvert.DeserializeObject<PixivTagJson.Root>(Shtml);
            if (AllJson.illust.Count > 0)
            {
                foreach (PixivTagJson.Illust Single in AllJson.illust)
                {
                    if (PixivStaticValue.ExcludeOpenFlag && JudgeTagAndUser(Single))
                    {
                        Console.WriteLine("检测到不合规定关键词，跳出");
                        continue;
                    }

                    if (!TempImgIDList.Contains(Single.illust_id))
                        TempImgIDList.Add(Single.illust_id);
                    else
                        return null;//不会出现重复的情况，如果出现则肯定是到最后一页了
                    if (Score == 0)
                        ImglistTemp.AddRange(new PixivHelper().QuickAnalysisAllImg(Single.illust_page_count, Single.url, Single.illust_id, Score.ToString()));
                    else
                        ImglistTemp.AddRange(new PixivHelper().SlowAnalysisAllImg(Score, Single.illust_page_count, Single.url, Single.illust_id));
                }
            }
            return ImglistTemp;
        }

        /// <summary>
        /// 判断tag和作者是否在黑名单
        /// </summary>
        /// <param name="single"></param>
        /// <returns></returns>
        private static bool JudgeTagAndUser(PixivTagJson.Illust single)
        {
            List<string> TagList = new List<string>();

            TagList.Add(single.illust_id + "");
            TagList.Add(single.illust_tag01);
            TagList.Add(single.illust_tag02);
            TagList.Add(single.illust_tag03);
            TagList.Add(single.illust_tag04);
            TagList.Add(single.illust_tag05);
            TagList.Add(single.illust_tag06);
            TagList.Add(single.illust_tag07);
            TagList.Add(single.illust_tag08);
            TagList.Add(single.illust_tag09);
            TagList.Add(single.illust_tag10);
            List<string> TempList = new List<string>();

            foreach (string line in TagList)
            {
                if (line != "")
                    TempList.Add(line);
            }
            return ListHelper.CompareRepetition(TempList, StaticValueOld.ExcludeList);
        }
    }
}